/* tcpmopen.c - tcpmopen */

#include "defines.h"
#include "tcpfms.h"
#include "tcb.h"
#include "tcp.h"

int tcpserver(struct tcb *, u_short);
int tcpbind(struct tcb *ptcb, ipaddr fip, u_short fport);
int tcpcon(struct tcb *);

/*------------------------------------------------------------------------
 *  tcpmopen  -  open a fresh TCP pseudo device and return descriptor
 *------------------------------------------------------------------------
 */
int tcpmopen(void *fport0, void *lport0)
{
	//char		*fport = (char *)fport0;
	int		lport = (int)lport0;
	struct	tcb	*ptcb;
	int		error;

	ptcb = (struct tcb *)tcballoc();
        
	if (ptcb == (struct tcb *)SYSERR)
            return SYSERR;
	ptcb->tcb_error = 0;
	//proctab[currpid].ptcpumode = 0;
	if ((int)fport0 == ANYPORT)
            return tcpserver(ptcb, lport);
        
	if (tcpbind(ptcb, (ipaddr)fport0, lport) != OK || tcpsync(ptcb) != OK) {
            ptcb->tcb_state = TCPS_FREE;
            sem_destroy(&(ptcb->tcb_mutex) );
            return SYSERR;
	}
	if ( (error = tcpcon(ptcb)) )
		return error;
	return ptcb->tcb_dvnum;
}
